<?php
namespace app\finance\model;
use think\Db;
use app\common\model\Common;
class Pay extends Common
{
	protected $table = 'mps_expend_log';
	protected $append = ['cat_name','supplier_name'];
	const all_pay = 0;//总部支出记账
	const shop_pay = 1;//门店支出记账
	const all_time = 2;//总部定期支付
	
	/**
	* 按月支出
	*/
	public function monthMoney()
	{
		$sql = $this->monthMoneySql();
		$data = Db::name('expendCate')->alias('ec')->join($sql,'el.expend_cate_id = ec.expend_cate_id','LEFT')
		->field('ec.cat_name,ifnull(sum(el.money),0) as money')
		->where('ec.ty',self::all_pay)
		->group('ec.expend_cate_id')
		->select();
		$num = intval(date('m'));
		foreach($data as $k => $v){
			$data[$k]['money'] = $this->doubleExcept($v['money'], $num);
		}
		return $data;
	}
	/**
	* 单笔支出
	*/
	public function singleMoney()
	{
		$data = Db::name('expendCate')->alias('ec')->join('mps_expend_log el','el.expend_cate_id = ec.expend_cate_id','LEFT')
		->field('ec.cat_name,ifnull(count(el.expend_id),0) as num,ifnull(sum(el.money),0) as money')
		->where('ec.ty',self::all_pay)
		->group('ec.expend_cate_id')
		->select();
		foreach($data as $k => $v){
			$data[$k]['money'] = $v['num'] == 0 ? 0 : $this->doubleExcept($v['money'], $v['num']);
		}
		return $data;
	}
	/**
	* 定期支付
	*/
	public function regularMoney()
	{
		return Db::name('expendCate')->alias('ec')->join('mps_expend_log el','el.expend_cate_id = ec.expend_cate_id','LEFT')
		->field('ec.cat_name,ifnull(sum(el.money),0) as money,ec.expend_cate_id')
		->where('ec.ty',self::all_time)
		->group('ec.expend_cate_id')
		->select();
	}
	/**
	* 支出总额
	 * @param array $where 查询条件
	 * @param string $order 排序条件
	 * @param string $search 关键字检索条件
	*/
	public function allMoney($where, $order, $search = '')
	{
		if($where === false) return 0;
		return $this->where($search)->where($where)->order($order)->sum('money');
	}
	/**
	* 获取供应商
	*/
	public function getSupplier()
	{
		return Db::name('supplier')->where('is_show',0)->select();
	}
	/**
	* 获取器
	*/
	public function getAddtimeAttr($value){
		return $value > 0 ? date('Y-m-d H:i:s',$value) : '---';
	}
	public function getCatNameAttr($value, $data){
		return Db::name('expendCate')->where('expend_cate_id',$data['expend_cate_id'])->value('cat_name');
	}
	public function getSupplierNameAttr($value, $data){
		return Db::name('supplier')->where('supplier_id',$data['supplier_id'])->value('supplier_name');
	}
	/************************************** 私有 ***************************************/
	/**
	* 本年支出
	*/
	private function monthMoneySql()
	{
		$sql = $this->field('expend_cate_id,money')->where('addtime','>=','strtotime(date("Y"))')->select(false);
		return "($sql) as el";
	}
	/**
	* 统计笔数
	*/
	private function singleMoneySql()
	{
		$sql = $this->field('expend_cate_id,count(expend_id) as num,sum(money) as money')->group('expend_cate_id')->select(false);
		return "($sql) as el";
	}
}